package com.yxy.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yxy.common.Result;
import com.yxy.constant.RequestMapperConstant;
import com.yxy.pojo.entity.CityInfo;
import com.yxy.pojo.entity.Music;
import com.yxy.pojo.vo.StatisticsVO;
import com.yxy.service.CommonService;
import com.yxy.service.GaudService;
import com.yxy.service.RouteService;
import com.yxy.service.SightsService;
import com.yxy.utils.QiniuOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping(RequestMapperConstant.COMMON_REQUEST_MAPPER)
@Slf4j
public class CommonController {

    private static final Map<Integer, String> m = new HashMap<>() {
        {
            put(1, "songName");
            put(2, "singer");
            put(3, "songId");
            put(4, "url");
        }
    };
    @Autowired
    private GaudService gaudService;
    @Autowired
    private CommonService commonService;

    /**
     * 文件上传 七牛云
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        log.info("文件名：{}", file.getOriginalFilename());
        String uploadFileName = QiniuOSSUtil.uploadToQiniu(file);
        return Result.success("上传成功", uploadFileName);
    }

    /**
     * 随机网易云音乐（素颜api）
     *
     * @return
     */
    @GetMapping("/getMusic")
    public Result<Map<String, Object>> getMusic() {
        log.info("获取歌曲");
        Map<String, Object> map = new HashMap<>();
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.suyanw.cn/api/neran.php"))
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            Gson gson = new Gson();
            Music music = gson.fromJson(response.body(), Music.class);
            map.put("songName", music.getName());
            map.put("songId", music.getId());
            map.put("url",music.getMp3url());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success("", map);
    }

    /**
     * 随机古诗词（素颜api）
     * @return
     */
    @GetMapping("/getShortSentence")
    public Result<String> getShortSentence(){
        log.info("获取古诗词");
        String str = "";
        try{
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.suyanw.cn/api/gushi.php"))
                    .header("Accept", "application/json")
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            str = response.body();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return Result.success("", str);
    }

    /**
     * 获取天气（高德api）
     * @return
     */
    @GetMapping("/getWeather")
    public Result<CityInfo> getWeather(String area){
        log.info("获取天气：{}", area);
        CityInfo cityInfo = null;
        // 查询数据库回去城市对应的adcode
        area = area.replace("省", "");
        int adcode = gaudService.getAdcodeByCityName(area);
        try{
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://restapi.amap.com/v3/weather/weatherInfo?city=" + adcode + "&key=0ce3760aec66e99aaf38d5387fcd3bd8"))
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(response.body(), JsonObject.class);
            cityInfo = gson.fromJson(jsonObject.getAsJsonArray("lives").get(0), CityInfo.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success("", cityInfo);
    }


    /**
     * 统计景点与线路访问量和景点与酒店预约量
     * @return
     */
    @GetMapping("/getStatistics")
    public Result<StatisticsVO> statistics(){
        log.info("统计景点与线路访问量和景点与酒店预约量");
        StatisticsVO vo = commonService.statistics();
        return Result.success("", vo);
    }
}
